package com.crr.controller;

import cn.hutool.core.bean.BeanUtil;
import com.crr.bean.Employee;
import com.crr.common.bean.PageBean;
import com.crr.common.bean.ResultBean;
import com.crr.common.controller.BaseController;
import com.crr.common.group.ISave;
import com.crr.common.group.IUpdate;
import com.crr.query.EmployeeQuery;
import com.crr.service.EmployeeService;
import com.crr.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = "员工管理")
@RequestMapping("v1")
@RestController
public class EmployeeController extends BaseController {
    @Autowired
    EmployeeService employeeService;
    @Autowired
    UserService userService;
    @ApiOperation("保存员工")
    @PostMapping("/employee")
    public ResultBean save(@Validated({ISave.class}) @RequestBody Employee employee, BindingResult result){
        validate(result);
        int res = userService.queryUserByAccount(employee.getUser().getAccount());
        if(res==1){
            return fail("用户名已被占用！");
        }
        int rs=employeeService.save(employee);
        return saveResult(rs);
    }
    @ApiOperation("查询员工")
    @PostMapping("/employee/query")
    public ResultBean query(@RequestBody EmployeeQuery query){
        PageBean bean= employeeService.query(BeanUtil.beanToMap(query));
        return success("员工列表",bean);
    }
    @ApiOperation("删除员工")
    @DeleteMapping("/employee")
    public ResultBean delete(@RequestParam(value = "id",required = true) int id){
       int res= employeeService.delete(id);
       return deleteResult(res);
    }
    @ApiOperation("修改员工")
    @PutMapping("/employee")
    public ResultBean update(@Validated({IUpdate.class}) @RequestBody Employee employee, BindingResult result){
        validate(result);
        int res = employeeService.update(employee);
        return updateResult(res);
    }
}
